package callAnalyzer.io;

import java.util.Date;
import java.sql.Timestamp;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.os.AsyncTask;
import android.util.Log;

import ca.uol.aig.fftpack.RealDoubleFFT; 
import utils.sound.RMS;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

public class Recorder {
	
	int audioSource;
	int sampleRateinHz;
	int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
	int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
	int bufferSizeInBytes;
	AudioRecord audioRecord;
	Boolean isRecording = false;
	RecordAudio recordTask;
	RealDoubleFFT transformer; // UNUSED
	int blocksize = 256;
	
	public Recorder(int audioSource, int sampleRateinHz){
		
		this.audioSource = audioSource;
		this.sampleRateinHz = sampleRateinHz;
		this.bufferSizeInBytes = AudioRecord.getMinBufferSize(this.sampleRateinHz, 
														this.channelConfig, 
														this.audioFormat);
		
		this.transformer = new RealDoubleFFT(this.blocksize); // UNUSED
	}
	
	public void record(){
		this.recordTask = new RecordAudio();
		this.recordTask.execute();
	}
	
	public void stoprecording(){
		this.isRecording = false;
	}
	
	private class RecordAudio extends AsyncTask<Void, Integer, Void>{
		
		@Override
		protected Void doInBackground(Void... params){
		    isRecording = true;
		    try{
		    	audioRecord = new AudioRecord(audioSource, 
		    								  sampleRateinHz,
		    								  channelConfig,
		    								  audioFormat,
		    								  bufferSizeInBytes);
		    	short[] buffer = new short[blocksize];
		    	double[] toTransform = new double[blocksize];
		    	Date date = new Date();
		    	Timestamp timestamp = new Timestamp(date.getTime());
		    	String timstamp_str = timestamp.toString();
		    	String to_write = "{timestamp:" + timstamp_str + ", phone:xxxxxxx123,data: "; 
		    	String data = "[";
		    	audioRecord.startRecording();
		    	while(isRecording){
		    		int bufferReaderResult = audioRecord.read(buffer, 0, blocksize);
		    		for(int i = 0; i < blocksize && i < bufferReaderResult; i ++){
		    			toTransform[i] = (double) buffer[i] / 32678.0; // signed 16 bit
		    		}
		    		data += Double.toString(RMS.rms(toTransform)) + ",";
		    	}
		    	audioRecord.stop();
		    	data += "]";
		    	to_write += data + "}";
//		    	try{
//		    		Log.d("RecordAudio", "EDW");
//		    		db.execSQL("INSERT INTO anal_data(analyzed_data)"+
//		    					"VALUES('" + to_write + "');");
//		    	}catch (SQLiteException se ) {
//		    		Log.e("RecordAudio", "Insert to database Failed");
//		    	}
		    	Log.d("RecordAudio", "Insert to database Success");
		    }catch(Throwable t){
		    	Log.e("RecordAudio", "Recording Failed");
		    }
			return null;
		}
		
	}
	
}